package com.caht.servier.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.caht.DTO.UserDTOS.FollowUserDTO;
import com.caht.Uilts.HttpClientUtil;
import com.caht.Uilts.ValidateCodeUtils;
import com.caht.VO.UserFollowVO;
import com.caht.context.BaseContext;
import com.caht.entity.User;
import com.caht.DTO.*;
import com.caht.mapper.UserMapper;
import com.caht.properties.WeChatProperties;
import com.caht.servier.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class UserServierImpl implements UserService {
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    //微信 配置信息
    @Autowired
    WeChatProperties weChatProperties;
    // mapper 接口
    @Autowired
    private UserMapper userMapper;

    /**
     * 获取 微信 openid
     *
     * @param code
     * @return
     */
    public String getOpenId(String code) {
        Map<String, String> stringMap = new HashMap<>();
        stringMap.put("appid", weChatProperties.getAppId());
        stringMap.put("secret", weChatProperties.getSecret());
        stringMap.put("js_code", code);
        stringMap.put("grant_type", "authorization_code");
        String s = HttpClientUtil.doGet(WX_LOGIN, stringMap);
        JSONObject jsonObject = JSON.parseObject(s);
        String openid = jsonObject.getString("openid");
        return openid;
    }

    /**
     * 获取手机验证码
     *
     * @param phone
     */
    public Integer GetPhoneCode(String phone) {
        Integer code = ValidateCodeUtils.generateValidateCode(4);//随机生成 验证码
        return code;
    }

    /**
     * 手机号登入
     *
     * @param userDTO
     * @return
     */
    public User phoneLogin(UserDTO userDTO) {
        userDTO.setLoginType(1L);
        User user = userMapper.getCode(userDTO);
        //判断数据中是否存在 不存向数据库中添加数据
        if (user == null) {
            user = new User();
            user.setLongType(1L);
            user.setPhone(userDTO.getPhone());
            user.setFollow(0);
            user.setBackgroundImage(userDTO.getAvatarUrl());
            userMapper.insert(user);
        }
        return user;
    }

    @Override
    public User wxLogin(UserDTO userDTO) {
        return null;
    }

    /**
     * 关注用户
     */
    @Override
    public List<UserFollowVO> getFollowUser(Long followingId) {
        // 返回给前端的数据
        List<UserFollowVO> userFollowVOList = new ArrayList<>();
        //当前用户 ID
        Long userId = BaseContext.getCurrentId();
        // 关注用户 ID
        List<UserFollowVO> followUser = userMapper.getFollowList(followingId, 0L);
        // 过滤出当前用户关注的用户
        List<UserFollowVO> filterFollowUser = followUser.stream()
                .filter(item ->
                        item.getFollowerId().equals(String.valueOf(userId)))
                .collect(Collectors.toList());
        // 过滤谁关注了当前用户
        List<UserFollowVO> followNotUserDTOS = followUser.stream()
                .filter(item ->
                        item.getFollowingId().equals(String.valueOf(userId)))
                .collect(Collectors.toList());
        // 处理互相关注的数据
        userFollowVOList = this.EachotherFollowUser(filterFollowUser, followNotUserDTOS);
        // 获取当前用户未关注的用户
        return userFollowVOList;
    }

    /**
     * 关注信息处理
     *
     * @param filterFollowUser  当前用户关注的用户
     * @param followNotUserDTOS 其他用户关注当前用户
     * @return
     */
    public List<UserFollowVO> EachotherFollowUser(List<UserFollowVO> filterFollowUser, List<UserFollowVO> followNotUserDTOS) {
        List<UserFollowVO> list = new ArrayList<>();
        // 通过当前用户关注的 用户去判断 其他用户是否关注了当前用户
        for (UserFollowVO followUserDTO : filterFollowUser) {
            for (UserFollowVO followNotUserDTO : followNotUserDTOS) {
                    if (followNotUserDTO.getFollowerId().equals(followUserDTO.getFollowingId())
                            &&
                            followNotUserDTO.getFollowingId().equals(followUserDTO.getFollowerId())
                    ) {
                        // 互相关注
                        followUserDTO.setFollowsStatus(2L);
                        list.add(followUserDTO);
                        followNotUserDTOS.remove(followNotUserDTO);
                        log.info("互相关注：{}", followUserDTO.getFollowerId());
                    }
                    // 未互相关注
                    else if (followNotUserDTO.getFollowingId().equals(followUserDTO.getFollowerId())) {
                        followNotUserDTO.setFollowsStatus(3L);
                        list.add(followNotUserDTO);
                        log.info("回关注：{}", followUserDTO.getFollowerId());
                    }
            }
            if (followUserDTO.getFollowsStatus() == null) {
                followUserDTO.setFollowsStatus(1L);
                list.add(followUserDTO);
                log.info("已关注：{}", followUserDTO.getFollowingId());
            }
        }
        return list;
    }
}
